

package com.linghu.dao;


import com.linghu.utils.JDBCUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author: Gin
 * @Description: BasicDAO：其他 DAO 类的父类
 * @Modified By: Gin
 * @Date: Created in 18:54 2021/9/15
 */
public class BasicDAO<T> {

    private QueryRunner queryRunner = new QueryRunner();

    // 开发通用的 DML 方法，针对任意的表
    public int update(String sql, Object... parameters){
        Connection connection = null;
        try{
            connection = JDBCUtilsByDruid.getConnection();
            int rows = queryRunner.update(connection, sql, parameters);
            return rows;
        } catch (SQLException e) {
            // 将编译异常转为运行异常抛出
            throw new RuntimeException(e);
        } finally {
            JDBCUtilsByDruid.close(null, null, connection);
        }
    }

    // 返回多个对象（即查询的结果是多行的），针对任意表
    /**
     * @param sql：SQL语句，可以有 ?
     * @param tClass：传入一个类的 Class 对象，比如 Actor.class
     * @param parameters：传入 ? 的具体值，可以有多个
     * @return 根据 Actor.class 返回对应的 ArrayList 集合
     */
    public List<T> queryMultiple(String sql, Class<T> tClass, Object... parameters){
        Connection connection = null;
        try{
            connection = JDBCUtilsByDruid.getConnection();
            List<T> query = queryRunner.query(connection, sql, new BeanListHandler<>(tClass), parameters);
            return query;
        } catch (SQLException e) {
            // 将编译异常转为运行异常
            throw new RuntimeException(e);
        } finally {
            JDBCUtilsByDruid.close(null, null, connection);
        }
    }

    // 查询单行结果
    public T querySingle(String sql, Class<T> tClass, Object... parameters){
        Connection connection = null;
        try{
            connection = JDBCUtilsByDruid.getConnection();
            T query = queryRunner.query(connection, sql, new BeanHandler<T>(tClass),parameters);
            return query;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtilsByDruid.close(null, null, connection);
        }
    }

    // 查询单行单列的方法，即返回的是单个值的方法
    public Object queryScalar(String sql, Object... parameters){
        Connection connection = null;
        try{
            connection = JDBCUtilsByDruid.getConnection();
            Object query = queryRunner.query(connection, sql, new ScalarHandler(), parameters);
            return query;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtilsByDruid.close(null, null, connection);
        }
    }


}



